snatch victory from the jaws of defeat
​to win something even though it seemed up until the last moment that you would lose
The idiom is often reversed for humorous effect to show that a person or team were expected to win, but then lost at the last moment, snatching defeat from the jaws of victory.